<?php

namespace app\api\service\alipay;

use app\api\service\Memberlevel as MemberlevelService;

use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

/**
 * 升级会员等级支付回调
 */
class MemberlevelNotify extends BaseNotify
{

    // 回调
    public function notify(){
        $data = $this->alipayNotify();

        // 写入日志
        $postXml = $this->arrayToXml($data);
        Log::record($postXml);

        Db::startTrans();
        try {
            // 验证签名
            if ($data['flag']) {
                // 商户订单号
                $orderNo = $data['out_trade_no'];
                // 交易状态
                $trade_status = $data['trade_status'];
                // 交易付款时间
                $paytime = $data['gmt_payment'];

                if ($trade_status == "TRADE_SUCCESS") {
                    $model = new \app\admin\model\Memberlevelrecord();
                    $order = $model->where('order_no', $orderNo)->find();
                    if (!$order) {
                        Log::record('订单不存在');
                        echo "fail";
                    }

                    if ($order->status != 1){
                        $param = new \stdClass();
                        $param->memberId = $order->member_id;
                        $param->levelId = $order->member_level_id;
                        $param->vip_cost = $order->money;
                        $param->vip_time = $order->level_time;
                        $param->pay_method = $order->pay_method;
                        // 开通成功后更新会员相关信息
                        $result = MemberlevelService::updateMember($param);
                        if ($result['code'] != 1) {
                            Log::record($result['msg']);
                            echo "fail";
                        }

                        // 更新订单状态
                        $result = $order->where('order_no', $orderNo)->update(['status' => 1, 'pay_date' => $paytime]);
                        if($result === false){
                            Log::record('更新订单状态失败');
                            echo "fail";
                        }
                    }

                    Db::commit();
                    echo "success";
                } else {
                    echo "fail";
                }
            } else {
                echo "fail";
            }
        } catch (Exception $e) {
            Db::rollback();
            Log::record($e->getMessage());
            echo "fail";
        }
    }
}